package com.eling.elcms.travel.webapp.controller;

import com.eling.elcms.basedoc.model.ContactAddress;
import com.eling.elcms.basedoc.model.ContactAddress.AddressStatus;
import com.eling.elcms.component.excel.Metals;
import com.eling.elcms.core.dao.hibernate.search.SearchCondition;
import com.eling.elcms.core.util.PropertyUtils;
import com.eling.elcms.core.webapp.controller.BaseFormController;
import com.eling.elcms.core.webapp.controller.Msg;
import com.eling.elcms.core.webapp.spring.ModelFilling;
import com.eling.elcms.core.webapp.util.ExcelUtils;
import com.eling.elcms.member.model.Member;
import com.eling.elcms.member.model.view.MemberToExcel;
import com.eling.elcms.travel.model.ProductBatch;
import com.eling.elcms.travel.model.ProductRuleDetail;
import com.eling.elcms.travel.model.TravelContract;
import com.eling.elcms.travel.model.view.*;
import com.eling.elcms.travel.service.ITravelContractManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class TravelContractController extends BaseFormController {
	
	@Autowired
	private ITravelContractManager travelContractManager;

	@RequestMapping("/api/travelcontract/query")
	@ResponseBody
	public List<TravelContract> query(@ModelAttribute TravelContract cond) {
		return travelContractManager.query(cond);
	}

	@RequestMapping("/api/travelcontract/search")
	@ResponseBody
	public List<TravelContract> search(@ModelAttribute SearchCondition sc, @ModelAttribute TravelContract cond) {
		sc.setQueryCondition(cond);
		return travelContractManager.search(sc);
	}

	@RequestMapping("/api/travelcontract/save")
	@ResponseBody
	public TravelContract save(@ModelAttribute @ModelFilling TravelContract travelContract) {
		return travelContractManager.save(travelContract);
	}

	@RequestMapping("/api/travelcontractcharge/saveall")
	@ResponseBody
	public TravelContract saveAll(@ModelAttribute TravelContract travelContract,
			@RequestParam(value = "isMem", required = false) Boolean isMem, 
			@RequestParam(value = "pkLong", required = false) Long pkLong
			) {
		return travelContractManager.saveAll(travelContract, isMem, pkLong);
	}

	@RequestMapping("/api/travelcontract/{pkTravelContract}/delete")
	@ResponseBody
	public Msg delete(@PathVariable Long pkTravelContract) {
		travelContractManager.remove(pkTravelContract);
		return new Msg("删除成功");
	}

	@RequestMapping("/api/travelcontract/queryproductbatch")
	@ResponseBody
	public List<ProductBatch> queryProductBatch(@ModelAttribute TravelContract cond) {
		return travelContractManager.queryProductBatch(cond);
	}
	
	@RequestMapping("/api/travelcontract/getproductdetail")
	@ResponseBody
	public ProductRuleDetail getProductDetail(@ModelAttribute TravelContract cond){
		return travelContractManager.getProductDetail(cond);
	}
	

	@RequestMapping("/api/travelcontract/{pkTravelContract}/deleteall")
	@ResponseBody
	public Msg deleteAll(@PathVariable Long pkTravelContract) {
		return travelContractManager.deleteAll(pkTravelContract);
	}

	/**
	 * 合同签约搜索会员及客户
	 * 
	 * @param sc
	 * @param tuView
	 * @return
	 * @author zhoulin
	 */
	@RequestMapping("/api/travelcontract/searchcontractuser")
	@ResponseBody
	public List<TravelUserView> searchContractUser(@ModelAttribute SearchCondition sc,
			@ModelAttribute TravelUserView tuView) {
		return travelContractManager.searchContractUser(sc, tuView);
	}
	
	/**
	 * 签约用户统计
	 * @author ZhaoYuJing
	 * @return 
	 */
	@RequestMapping("/api/travelcontract/queryCount")
	@ResponseBody
	public List<ContractStatView> countValid(@RequestParam("signUpDate") Date signUpDate,
											 @RequestParam("signUpDateEnd") Date signUpDateEnd){
		return travelContractManager.countValid(signUpDate,signUpDateEnd);
	}
	
	
	/**
	 * 查询签约会员
	 * @author ZhaoYuJing
	 * @return
	 */
	@RequestMapping("/api/travelcontract/queryContractValid")
	@ResponseBody
	public List<contractGridValid> contractValid(@RequestParam(value="pkProduct") Long pkProduct,
												 @RequestParam(value="pkProductType") Long pkProductType,
												 @RequestParam("signUpDate") Date signUpDate,
												 @RequestParam("signUpDateEnd") Date signUpDateEnd){
		return travelContractManager.contractValid(pkProduct,pkProductType, signUpDate,signUpDateEnd);
	}
	
	/**
	 * 查询会员证号（只查询闲置状态的会员证）
	 * @author XueChao
	 * @return
	 */
	@RequestMapping("/api/travelcontract/queryIdle")
	@ResponseBody
	public List<TravelContractView> queryIdle(@ModelAttribute TravelContractView cond) throws Exception{
		
		return travelContractManager.queryIdle(cond);
	}
	
	
	/**
	 * 退证申请 新增时搜索会员证号或合同号
	 * **/
	@RequestMapping("/api/travelcontract/querybycard")
	@ResponseBody
	public ReturnCredentialsView queryByCard(@ModelAttribute TravelContract cond,
			@RequestParam(value="pkReturnCredentials",required = false) Long pkReturnCredentials,
			@RequestParam(value="flag",required = false,defaultValue="false") Boolean flag) {
		return travelContractManager.queryByCard(cond,pkReturnCredentials,flag);
	}
	
	/**
	 * 会员基本信息
	 */
	@RequestMapping("/api/member/queryallmember")
	@ResponseBody
	public List<Member> pageQueryByPoint(@ModelAttribute Member cond,
    		@RequestParam(value ="pkCommunityData" ,required=false) Long pkCommunityData,
    		@RequestParam(value ="pkServicePoint",required=false) Long pkServicePoint,
    		@RequestParam(value ="pkInterest",required=false) Long pkInterest,
    		@RequestParam(value ="pkOrg",required=false) String pkOrg,
    		@RequestParam(value ="exitMember")Boolean exitMember) {
		return travelContractManager.pageQueryByPoint(cond,pkCommunityData,pkServicePoint,pkInterest,pkOrg,exitMember); 
	}
	
	/**
	  *根据会员证号查询
	 */
	 
	@RequestMapping("/api/travelcontract/searchByMemberCertificates")
	@ResponseBody
	public TravelContractView searchByMemberCertificates(@RequestParam( value="s",required=false) String memberCertificates){
		TravelContractView travelContract = travelContractManager.searchByMemberCertificates(memberCertificates);
		return travelContract ;
	}
	
	/**
	 * 会员基本信息&退证会员档案    搜索
	 */
	@RequestMapping("/api/member/searchallmemberbycard")
	@ResponseBody
	public List<Member> searchMemPagingWithCard(
			@ModelAttribute SearchCondition sc,
			@ModelAttribute Member cond,
			@RequestParam(value ="pkCommunityData" ,required=false) Long pkCommunityData,
    		@RequestParam(value ="pkServicePoint",required=false) Long pkServicePoint,
    		@RequestParam(value ="pkInterest",required=false) Long pkInterest,
    		@RequestParam(value ="pkOrg",required=false) String pkOrg,
    		@RequestParam(value ="exitMember")Boolean exitMember) {
		return travelContractManager.searchMemPagingWithCard(sc,cond,pkCommunityData,pkServicePoint,pkInterest,pkOrg,exitMember); 
	}
	/**
	 * 导出
	 */
	 @RequestMapping("/api/member/tomemberexcel")
	   	@ResponseBody
	   	public void toExcelTravel(@ModelAttribute Member cond,
	    		@RequestParam(value ="pkCommunityData" ,required=false) Long pkCommunityData,
	    		@RequestParam(value ="pkServicePoint",required=false) Long pkServicePoints,
	    		@RequestParam(value ="pkInterest",required=false) Long pkInterest,
	    		@RequestParam(value ="pkOrg",required=false) String pkOrg,
	    		@RequestParam(value ="exitMember")Boolean exitMember,
	    		HttpServletResponse resp){
	    	String fetchProperties = "pkMember"+
	    			"personalInfo.name,"+
	    			"personalInfo.sex.*," +
	    			"personalInfo.birthday," +
	    			"personalInfo.idType.*," +
	    			"personalInfo.idNumber," +
	    			"memberNumber,"+
	    			"interest.name,"+
	    			"personalInfo," +
	    			"personalInfo.phone," +
	    			"personalInfo.mobilePhone," +
	    			"status.*," +
	    			"personalInfo.contactAddresses.communityData.name," +
	    			"personalInfo.contactAddresses.buildingNumber," +
	    			"personalInfo.contactAddresses.unitNumber," +
	    			"personalInfo.contactAddresses.addressStatus.*," +
	    			"personalInfo.contactAddresses.version,";
	    	PropertyUtils.setProperty(cond, "fetchProperties", fetchProperties);
	    	List<Member> list=  pageQueryByPoint(cond, pkCommunityData, pkServicePoints, pkInterest, pkOrg,exitMember); 
	    	List<MemberToExcel> excel = new ArrayList<>();
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    	for(int i = 0;i<list.size(); i++){
	    		Member member = list.get(i);
	    		MemberToExcel example = new MemberToExcel();
//	    		long day=(new Date().getTime()-member.getPersonalInfo().getBirthday().getTime())/(24*60*60*1000) + 1;
//	    		example.setAge(new java.text.DecimalFormat("#").format(day/365f));
	    		if(member.getPersonalInfo().getBirthday()!=null){
	    			example.setAge(getAge(member.getPersonalInfo().getBirthday()));
	    			example.setBirthday(sdf.format(member.getPersonalInfo().getBirthday()));
	    		}
	    		example.setCard(member.getMemberNumber());
	    		example.setIdnumber(member.getPersonalInfo().getIdNumber());
	    		if(member.getPersonalInfo().getIdType()!=null){
	    			example.setIdtype(member.getPersonalInfo().getIdType().getDisplay());
	    		}
	    		example.setMobilephone(member.getPersonalInfo().getMobilePhone());
	    		example.setName(member.getPersonalInfo().getName());
	    		example.setPhone(member.getPersonalInfo().getPhone());
	    		example.setSex(member.getPersonalInfo().getSex()!=null?member.getPersonalInfo().getSex().getDisplay():null);
	    		example.setStatus(member.getStatus().getDisplay());
	    		Set<ContactAddress> address = member.getPersonalInfo().getContactAddresses();
	    		String addres = "";
				for(ContactAddress add:address){
					if(add!=null && add.getAddressStatus().equals(AddressStatus.DefaultAddress)){
	    				if(StringUtils.isNotBlank(add.getDetailAddress())){
	    					addres = addres +add.getDetailAddress();
	    				}
	    			}
	    		}
	    		example.setAddress(addres);
	    		excel.add(example);
	    	}
	    	Map<String,Object> data = new  HashMap<String,Object>();
			data.put("list", excel);	
			data.put("title", "会员基本信息");
			Properties prop = new Properties();
			prop.setProperty(Metals.DEFAULT_DATE_FORMAT, "yyyy-MM-dd");
			String templateLoacation = "classpath:com/eling/elcms/member/excel/membertravel.xlsx";
			ExcelUtils.mergeForDownload(templateLoacation, data,"会员信息.xlsx", prop,resp);
	   	}
	    public  String getAge(Date birthDay) { 
	        Calendar cal = Calendar.getInstance(); 
	        int yearNow = cal.get(Calendar.YEAR); 
	        int monthNow = cal.get(Calendar.MONTH)+1; 
	        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); 
	        
	        cal.setTime(birthDay); 
	        int yearBirth = cal.get(Calendar.YEAR); 
	        int monthBirth = cal.get(Calendar.MONTH); 
	        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); 

	        int age = yearNow - yearBirth; 

	        if (monthNow <= monthBirth) { 
	            if (monthNow == monthBirth) { 
	                //monthNow==monthBirth 
	                if (dayOfMonthNow < dayOfMonthBirth) { 
	                    age--; 
	                } 
	            } else { 
	                //monthNow>monthBirth 
	                age--; 
	            } 
	        } 
	        return age +""; 
	    }
	
}
